{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "28e130e3",
   "metadata": {},
   "source": [
    "## CSV解析器\n",
    "\n",
    "当您想要返回以逗号分隔的项目列表时，可以使用此输出解析器。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8e483375",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='每只兔子有4条腿，所以2只兔子共有8条腿。')"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "openai_api_key = \"EMPTY\"\n",
    "openai_api_base = \"http://127.0.0.1:1234/v1\"\n",
    "chat = ChatOpenAI(\n",
    "    openai_api_key=openai_api_key,\n",
    "    openai_api_base=openai_api_base,\n",
    "    temperature=0.3,\n",
    ")\n",
    "\n",
    "chat.invoke(\"请问2只兔子有多少条腿？\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "e66461d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.output_parsers import CommaSeparatedListOutputParser\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "output_parser = CommaSeparatedListOutputParser()\n",
    "\n",
    "# format_instructions = output_parser.get_format_instructions()\n",
    "format_instructions = \"您的响应应该是csv格式的逗号分隔值的列表，例如：`内容1, 内容2, 内容3`\"\n",
    "prompt = PromptTemplate(\n",
    "    template=\"{format_instructions}\\n请列出五个 {subject}.\",\n",
    "    input_variables=[\"subject\"],\n",
    "    partial_variables={\"format_instructions\": format_instructions},\n",
    ")\n",
    "\n",
    "\n",
    "\n",
    "chain = prompt | chat | output_parser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "f95506fd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Your response should be a list of comma separated values, eg: `foo, bar, baz`'"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "format_instructions = output_parser.get_format_instructions()\n",
    "format_instructions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "252168a8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['香草', '巧克力', '草莓', '抹茶', '薄荷']"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.invoke({\"subject\": \"冰淇淋口味\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "1787942c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "StringPromptValue(text='您的响应应该是csv格式的逗号分隔值的列表，例如：`内容1, 内容2, 内容3`\\n请列出五个 冰淇淋口味.')"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt.invoke({\"subject\": \"冰淇淋口味\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3013e8a",
   "metadata": {},
   "source": [
    "## 日期时间解析器\n",
    "此 OutputParser 可用于将 LLM 输出解析为日期时间格式。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "b57ad65c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "output_parser = DatetimeOutputParser()\n",
    "template = \"\"\"回答用户的问题:\n",
    "\n",
    "{question}\n",
    "\n",
    "{format_instructions}\"\"\"\n",
    "\n",
    "\n",
    "format_instructions=output_parser.get_format_instructions()\n",
    "\n",
    "format_instructions='''响应的格式用日期时间字符串:“%Y-%m-%dT%H:%M:%S.%fZ”。\n",
    "\n",
    "示例: 1898-05-31T06:59:40.248940Z, 1808- 10-20T01:56:09.167633Z、0226-10-17T06:18:24.192024Z\n",
    "\n",
    "仅返回此字符串，没有其他单词！'''\n",
    "prompt = PromptTemplate.from_template(\n",
    "    template,\n",
    "    partial_variables={\"format_instructions\":format_instructions },\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "f3f57297",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Write a datetime string that matches the following pattern: '%Y-%m-%dT%H:%M:%S.%fZ'.\\n\\nExamples: 1898-05-31T06:59:40.248940Z, 1808-10-20T01:56:09.167633Z, 0226-10-17T06:18:24.192024Z\\n\\nReturn ONLY this string, no other words!\""
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "format_instructions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "2458304d",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = prompt | chat | output_parser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "29b108bb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2009, 1, 3, 18, 15)"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output = chain.invoke({\"question\": \"比特币是什么时候创立的？\"})\n",
    "output"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffc246ac",
   "metadata": {},
   "source": [
    "## Enum parser 枚举解析器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "9181c0ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.output_parsers.enum import EnumOutputParser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "c76bd9a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Enum\n",
    "\n",
    "class Colors(Enum):\n",
    "    RED = \"红色\"\n",
    "    BROWN = \"棕色\"\n",
    "    BLACK = \"黑色\"\n",
    "    WHITE = \"白色\"\n",
    "    YELLOW = \"黄色\"\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "6473a90e",
   "metadata": {},
   "outputs": [],
   "source": [
    "parser = EnumOutputParser(enum=Colors)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "53c3a7f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "promptTemplate = PromptTemplate.from_template(\n",
    "    \"\"\"{person}的皮肤主要是什么颜色？\n",
    "\n",
    "{instructions}\"\"\"\n",
    ")\n",
    "\n",
    "# instructions=parser.get_format_instructions()\n",
    "instructions = \"响应的结果请选择以下选项之一：红色、棕色、黑色、白色、黄色。不要有其他的内容\"\n",
    "prompt = promptTemplate.partial(instructions=instructions)\n",
    "chain = prompt | chat | parser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "c9360875",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Select one of the following options: 红色, 棕色, 黑色, 白色, 黄色'"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "instructions=parser.get_format_instructions()\n",
    "instructions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "f1405d42",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Colors.YELLOW: '黄色'>"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.invoke({\"person\": \"亚洲人\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d89b4f08",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
